package com.telit.common.util;

import com.telit.common.exception.ForestBaseException;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Calendar;
import java.util.Date;


/**
 * @author zhouyu
 * @description 时间工具类
 **/
public class TimeUtils {

    /**
     * 获取相隔天数
     * @return
     */
    public static Long getSeparatedDate(Date dateTime){
        LocalDate nowDate = LocalDate.now();
        LocalDate validateDate = dateTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        Long separatedDate = validateDate.toEpochDay()-nowDate.toEpochDay();
        if(separatedDate < 0L){
            separatedDate = 0L;
        }
        return separatedDate;
    }

    /**
     * 获取当前时间
     * @return
     */
    public static String getCurrentTime(){
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        Calendar calendar = Calendar.getInstance();
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND));
        return df.format(calendar.getTime());
    }

    public static String getMouthAgoTime(){
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        Calendar calendar = Calendar.getInstance();
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND));
        calendar.add(Calendar.MONTH, -1);
        return df.format(calendar.getTime());
    }


    public static String getCurrentTime0(){
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        Calendar calendar = Calendar.getInstance();
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND));
        return df.format(calendar.getTime());
    }

    public static String getMouthAgoTime0(){
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        Calendar calendar = Calendar.getInstance();
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.add(Calendar.MONTH, -1);
        return df.format(calendar.getTime());
    }


    public static String setDuringTime(Date startTime, Date endTime) {
        String duringTime="";
        long during = endTime.getTime() - startTime.getTime();
        if (during < 0) {
            return null;
        }
        long day = during / 86400000;
        long hour = (during - day * 86400000) / 3600000;
        long min = (during - day * 86400000 - hour * 3600000) / 60000;
        long sec = (during - day * 86400000 - hour * 3600000 - min * 60000) / 1000;
        if (day != 0) {
            duringTime = day + "天";
        }
        if (hour != 0) {
            duringTime = duringTime + hour + "时";
        }
        if (min != 0) {
            duringTime = duringTime + min + "分";
        }
        if (sec != 0) {
            duringTime = duringTime + sec + "秒";
        }
        if (duringTime.length() > 1 && duringTime.contains("-")) {
            duringTime = duringTime.replace("-", "");
        }
        return duringTime;
    }

    /**
     * 秒转hh:mm:ss格式
     * @param secString 秒字符串
     * @return hh小时mm分ss秒
     * String
     */
    public static String secondsToFormat(String secString){
        // 如果为空直接返回
        if(StringUtils.isEmpty(secString)){
            return null;
        }

        Integer seconds = Integer.parseInt(secString);
        Integer hour =0;
        Integer min =0;
        Integer second =0;
        String result ="";
        // 若时间小于一分钟直接返回
        if(seconds < 60){
            return  seconds + "秒";
        }

        if (seconds>=60) {   //是否大于等于零
            min = seconds/60;  //分钟
            second = seconds%60;  //秒
            if (min>=60) {   //存在时,60分算为一个小时
                hour=min/60;
                min=min%60;
            }
        }
        if (hour>0) {
            result=hour+"小时";
        }
        if (min>0) {
            result=result+min+"分";
        }else if (min==0&&hour>0 && second > 0) {  //当分为0时,但是时有值,且秒无值，所以要显示,避免出现2时0秒现象或者2时0分情况
            result=result+min+"分";
        }
        //秒必须大于0才显示
        if(second > 0){
            result=result+second+"秒";
        }

        return result;
    }

    public static String convertTime(String source){
        SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmss");
        try {
            Date s = df1.parse(source);
            return df2.format(s);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Date convertToDate(String source){
        SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return df1.parse(source);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Long convertTimeStamp(String source){
        SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date s = df1.parse(source);
            long time = s.getTime();
            return Math.round(time*1.0/1000L);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String convertFileNameTime(String source){
        SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmss");
        try {
            Date s = df1.parse(source);
            return df2.format(s) ;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String convertFileNameTime(Date source){
        SimpleDateFormat df1 = new SimpleDateFormat("yyyyMMddHHmmss");
        return df1.format(source);
    }

    public static Date convertToCameraFindTime(String source){
        SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        try {
            return df1.parse(source);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String convertToCameraFileNameTime(String source){
        SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmss");
        try {
            Date s = df1.parse(source);
            return df2.format(s) ;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String convertIOS8601Time(String source){
        SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
        try {
            Date s = df1.parse(source);
            return df2.format(s);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String convertIOS8601Time2(String source){
        SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZ");
        try {
            Date s = df1.parse(source);
            return df2.format(s);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 秒转换成小时
     * @return
     */
    public static String secondsToHour(String second){
        try {
            if (StringUtils.isEmpty(second)) {
                return null;
            }
            Integer seconds = Integer.parseInt(second);
            DecimalFormat df = new DecimalFormat("0.000");
            String hourStr = df.format(seconds / 3600F);
            return hourStr;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 秒转换成分钟
     *
     * @return
     */
    public static String secondsToMinutes(String second) {
        try {
            if (StringUtils.isEmpty(second)) {
                return null;
            }
            int seconds = Integer.parseInt(second);
            return BigDecimal.valueOf(seconds).divide(BigDecimal.valueOf(60), 1, RoundingMode.HALF_UP).toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 针对 2019-09-25T14:17:32.000+08:00 格式转换
     *
     * @param source
     *
     * @return
     */
    public static Date convertStandtardTime(String source) {
        SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
        SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date s = df1.parse(source);
            return s;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 针对 2023-03-13T18:54:22+08:00 格式转换
     * @param source
     * @return
     */
    public static Date convertStandtardTime2(String source){
        SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date s = df1.parse(source);
            return s ;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String convertFireNameTime(String source){
        SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
        SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmss");
        try {
            Date s = df1.parse(source);
            return df2.format(s);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String convertStringTime(Date date){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return df.format(date);
    }

    public static Date convertStringToTime(String date) throws ParseException {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return df.parse(date);
    }

    public static Date convertStringToTime2(String date) throws ParseException {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return df.parse(date);
    }


    /**
     * 获取当天00：00：00时间
     * @return
     */
    public static Date getCurrentDayZeroTime(){
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

    /**
     * 获取当月00：00：00时间
     * @return
     */
    public static Date getCurrentMonthZeroTime(){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar.getTime();
    }

    /**
     * 获取当年00：00：00时间
     * @return
     */
    public static Date getCurrentYearZeroTime(){
        Calendar currCal=Calendar.getInstance();
        int currentYear = currCal.get(Calendar.YEAR);
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, currentYear);
        Date currYearFirst = calendar.getTime();
        return currYearFirst;
    }

    public static void main(String[] args) {
        System.out.println(getCurrentYearZeroTime());
    }
    /**
     * 获得指定日期的前一天
     * @param date
     * @return
     */
    public static String getSpecifiedDayBefore(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        int day = c.get(Calendar.DATE);
        c.set(Calendar.DATE, day - 1);
        String dayBefore = new SimpleDateFormat("yyyyMMddHHmmss").format(c.getTime());
        return dayBefore;

    }

    /**
     * 获得指定日期的后一天
     * @param date
     * @return
     */
    public static String getSpecifiedDayAfter(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        int day = c.get(Calendar.DATE);
        c.set(Calendar.DATE, day + 1);
        String dayAfter = new SimpleDateFormat("yyyyMMddHHmmss")
                .format(c.getTime());
        return dayAfter;
    }


    public static String getYear(String date) throws ParseException {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat df1 = new SimpleDateFormat("yyyy");
        Date parse = df.parse(date);
        String format = df1.format(parse);
        return format;
    }

    public static String getMonth(String date) throws ParseException {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat df1 = new SimpleDateFormat("MM");
        Date parse = df.parse(date);
        String format = df1.format(parse);
        return format;
    }
    public static String getDay(String date) throws ParseException {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat df1 = new SimpleDateFormat("dd");
        Date parse = df.parse(date);
        String format = df1.format(parse);
        return format;
    }
    public static String getHour(String date) throws ParseException {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat df1 = new SimpleDateFormat("HH");
        Date parse = df.parse(date);
        String format = df1.format(parse);
        return format;
    }
    public static String getMinute(String date) throws ParseException {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat df1 = new SimpleDateFormat("mm");
        Date parse = df.parse(date);
        String format = df1.format(parse);
        return format;
    }
    public static String getSecond(String date) throws ParseException {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat df1 = new SimpleDateFormat("ss");
        Date parse = df.parse(date);
        String format = df1.format(parse);
        return format;
    }

    public static  int getAge(Date birthDay){
        if(birthDay == null){
            return 0;
        }
        Calendar cal = Calendar.getInstance();
        if (cal.before(birthDay)) { //出生日期晚于当前时间，无法计算
            throw new ForestBaseException("当前日期必须早于出生日期");
        }
        int yearNow = cal.get(Calendar.YEAR);  //当前年份
        int monthNow = cal.get(Calendar.MONTH);  //当前月份
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); //当前日期
        cal.setTime(birthDay);
        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
        int age = yearNow - yearBirth;   //计算整岁数
        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) {
                    age--;//当前日期在生日之前，年龄减一
                }
            } else {
                age--;//当前月份在生日之前，年龄减一
            }
        }
        return age;
    }

    /**
     * 获取当前时间后15min
     *
     * @return
     * @throws ParseException
     */
    public static Date getFiveMinAfter() throws ParseException {
        Date d = new Date();
        Calendar now = Calendar.getInstance();
        now.setTime(d);
        now.add(Calendar.MINUTE, 15);
        Date afterFiveMin = now.getTime();
        return afterFiveMin;
    }

    public static double compareDate(String strtime, String endtime) {
        String t1 = strtime;
        String t2 = endtime;
        Date d1 = null;
        Date d2 = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            d1 = sdf.parse(strtime);
            d2 = sdf.parse(endtime);
        } catch (ParseException pe) {
            System.out.println(pe.getMessage());
        }
        long dd1 = d1.getTime();
        long dd2 = d2.getTime();
        double hours = (double) (dd2 - dd1) / 3600 / 1000;
        return hours;
    }

    public static String dateStr(Date date){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return df.format(date);
    }

    /**
     * LocalDateTime转为日期
     *
     * @param localDateTime LocalDateTime
     * @return 日期
     */
    public static Date localDateTimeToDate(final LocalDateTime localDateTime) {
        if (null == localDateTime) {
            return null;
        }
        final ZoneId zoneId = ZoneId.systemDefault();
        final ZonedDateTime zdt = localDateTime.atZone(zoneId);
        final Date date = Date.from(zdt.toInstant());
        return date;
    }

}
